package com.dianban.controller.nengliang;

import com.dianban.base.ResultCode;
import com.dianban.base.ResultVo;
import com.dianban.config.redis.RedisConstant;
import com.dianban.config.redis.RedisUtil;
import com.dianban.controller.BaseController;
import com.dianban.entity.JwShoproUserAddress;
import com.dianban.entity.User;
import com.dianban.service.JwShoproAreaService;
import com.dianban.service.JwShoproUserAddressService;
import com.dianban.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Api(value = "ApiUserAddressController", description = "用户收货地址控制器")
@RestController
@RequestMapping(value = "${interfacePath}/nengliang/address/")
public class ApiUserAddressController extends BaseController {

    @Autowired
    private JwShoproUserAddressService jwShoproUserAddressService;
    @Autowired
    private JwShoproAreaService jwShoproAreaService;

    @ApiOperation(notes = "list", httpMethod = "GET", value = "获取我的所有收货地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
    })
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ResultVo list(HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        List<JwShoproUserAddress> addressList = new ArrayList<>();
        try {
            addressList = jwShoproUserAddressService.findList(user.getId());
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "获取失败");
        }
        return ResultVo.success(addressList, "获取成功");
    }

    @ApiOperation(notes = "info", httpMethod = "GET", value = "收货地址详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "string"),
    })
    @RequestMapping(value = "info", method = RequestMethod.GET)
    public ResultVo info(String id, HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        JwShoproUserAddress jwShoproUserAddress = null;
        try {
            jwShoproUserAddress = jwShoproUserAddressService.findById(id);
            if (jwShoproUserAddress == null) {
                return ResultVo.error(ResultCode.ERROR, "不存在该id的收货地址");
            }
            if (!jwShoproUserAddress.getUserId().equals(user.getId())) {
                return ResultVo.error(ResultCode.ERROR, "没有该数据的用户操作权限");
            }
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "操作失败");
        }
        return ResultVo.success(jwShoproUserAddress, "操作成功");
    }

    @ApiOperation(notes = "add", httpMethod = "POST", value = "添加收货地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "consignee", value = "收货人", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "phone", value = "收货人联系电话", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "province", value = "省", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "city", value = "市", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "area", value = "区", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "address", value = "详细地址", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "isDefault", value = "是否默认，1是，0否", required = true, paramType = "query", dataType = "string"),
    })
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public ResultVo add(String consignee, String phone, String province, String city, String area, String address, String isDefault, HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        try {
            if (StringUtils.isNotBlank(isDefault) && "1".equals(isDefault)) {
                // 更新所有的地址isDefault为0
                jwShoproUserAddressService.updateIsDefault("0", user.getId());
            }
            // 查询省市区具体名称
//            JwShoproArea province = jwShoproAreaService.findById(provinceId);
//            if (province == null) {
//                return ResultVo.error(ResultCode.ERROR, "省id数据不对");
//            }
//            JwShoproArea city = jwShoproAreaService.findById(cityId);
//            if (city == null) {
//                return ResultVo.error(ResultCode.ERROR, "市id数据不对");
//            }
//            JwShoproArea area = jwShoproAreaService.findById(areaId);
//            if (area == null) {
//                return ResultVo.error(ResultCode.ERROR, "区id数据不对");
//            }
            JwShoproUserAddress jwShoproUserAddress = new JwShoproUserAddress();
            jwShoproUserAddress.setIsDefault(isDefault);
            jwShoproUserAddress.setUserId(user.getId());
            jwShoproUserAddress.setConsignee(consignee);
            jwShoproUserAddress.setPhone(phone);
            jwShoproUserAddress.setAddress(address);
            jwShoproUserAddress.setProvinceName(province);
            jwShoproUserAddress.setCityName(city);
            jwShoproUserAddress.setAreaName(area);
            jwShoproUserAddressService.insert(jwShoproUserAddress);
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "操作失败");
        }
        return ResultVo.success("", "操作成功");
    }

    @ApiOperation(notes = "update", httpMethod = "POST", value = "修改收货地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "consignee", value = "收货人", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "phone", value = "收货人联系电话", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "province", value = "省", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "city", value = "市", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "area", value = "区", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "address", value = "详细地址", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "isDefault", value = "是否默认，1是，0否", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "id", value = "修改id", required = true, paramType = "query", dataType = "string"),
    })
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public ResultVo update(String consignee, String phone, String province, String city, String area, String address, String isDefault, String id, HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        try {
            JwShoproUserAddress jwShoproUserAddress = jwShoproUserAddressService.findById(id);
            if (jwShoproUserAddress == null) {
                return ResultVo.error(ResultCode.ERROR, "不存在该id的收货地址");
            }
            if (!jwShoproUserAddress.getUserId().equals(user.getId())) {
                return ResultVo.error(ResultCode.ERROR, "没有该数据的用户操作权限");
            }
            if (StringUtils.isNotBlank(isDefault) && "1".equals(isDefault)) {
                // 更新所有的地址isDefault为0
                jwShoproUserAddressService.updateIsDefault("0", user.getId());
            }
            // 查询省市区具体名称
//            JwShoproArea province = jwShoproAreaService.findById(provinceId);
//            if (province == null) {
//                return ResultVo.error(ResultCode.ERROR, "省id数据不对");
//            }
//            JwShoproArea city = jwShoproAreaService.findById(cityId);
//            if (city == null) {
//                return ResultVo.error(ResultCode.ERROR, "市id数据不对");
//            }
//            JwShoproArea area = jwShoproAreaService.findById(areaId);
//            if (area == null) {
//                return ResultVo.error(ResultCode.ERROR, "区id数据不对");
//            }
            jwShoproUserAddress.setIsDefault(isDefault);
            jwShoproUserAddress.setUserId(user.getId());
            jwShoproUserAddress.setConsignee(consignee);
            jwShoproUserAddress.setPhone(phone);
            jwShoproUserAddress.setAddress(address);
            jwShoproUserAddress.setProvinceName(province);
            jwShoproUserAddress.setCityName(city);
            jwShoproUserAddress.setAreaName(area);
            jwShoproUserAddressService.update(jwShoproUserAddress);
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "操作失败");
        }
        return ResultVo.success("", "操作成功");
    }

    @ApiOperation(notes = "delete", httpMethod = "GET", value = "删除收货地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "id", value = "修改id", required = true, paramType = "query", dataType = "string"),
    })
    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public ResultVo update(String id, HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        try {
            JwShoproUserAddress jwShoproUserAddress = jwShoproUserAddressService.findById(id);
            if (jwShoproUserAddress == null) {
                return ResultVo.error(ResultCode.ERROR, "不存在该id的收货地址");
            }
            if (!jwShoproUserAddress.getUserId().equals(user.getId())) {
                return ResultVo.error(ResultCode.ERROR, "没有该数据的用户操作权限");
            }
            jwShoproUserAddressService.deleteById(id);
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "操作失败");
        }
        return ResultVo.success("", "操作成功");
    }

}
